package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.SkuStockService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ProductReceiver {

    @Autowired
    private SkuStockService skuStockService;

    /**
     * 解锁库存
     * @param orderNo 订单号
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, type = "direct", durable = "true"),
            key = MqConst.ROUTING_UNLOCK,
            value = @Queue(value = MqConst.QUEUE_UNLOCK, durable = "true")
    ))
    public void unlock(String orderNo, Message msg, Channel channel) {

        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            log.info("解锁库存......" + orderNo);
            skuStockService.unlock(orderNo);

            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(deliveryTag, false, false);
        }
    }

    /**
     * 扣减库存
     *
     * @param orderNo
     * @param message
     * @param channel
     */

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_MINUS, durable = "true"),
            key = {MqConst.ROUTING_MINUS}
    ))
    public void minus(String orderNo, Message message, Channel channel) {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //String orderNo = new String(msg.getBody());
            log.info("扣减库存......" + orderNo);
            skuStockService.minus(orderNo);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(deliveryTag, false, false);
        }
    }
}